package com.example.yuntiku.dao.impl;

import com.example.yuntiku.dao.BaseDao;
import com.example.yuntiku.dao.ClassDao;
import com.example.yuntiku.entity.Class;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ClassDaoImpl extends BaseDao implements ClassDao {

    @Override
    public List<Class> selectAll() {
        List<Class> list=new ArrayList<>();
        String sql="SELECT `cid`,`cname` FROM `class`";
        ResultSet rs=null;
        try {
            rs=super.executeQuery(sql);
            while (rs.next()) { //一次读取一行记录，读完返回false
                //转换成实体类对象，一个对象，装一条数据
                Class entity = new Class();
                entity.setCid(rs.getInt("cid"));
                entity.setCname(rs.getString("cname"));
                //添加到集合
                list.add(entity);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            super.closeAll(conn,null,rs);
        }
        return list;
    }
    @Override
    public List<Class> queryClassByCid(String[] sids, String cid) {
        List<Class> list = new ArrayList<>();
        ResultSet rs = null;
        List<Object> params = new ArrayList<>();
        try {
            String sql="SELECT uid FROM `users` WHERE 1=1";
            if(cid != null){
                sql += " AND cid = IN (";
                params.add(cid);
            }
            for (String sid : sids) {
                //查询班级的学生
                sql+="?,";
                params.add(sid);
            }
            sql=sql.substring(0,sql.length()-1);//去掉最后一个，逗号
            sql+=" )";
            rs = super.executeQuery(sql, params.toArray());
            while (rs.next()){
                Class aClass = new Class();
                aClass.setCid(rs.getInt("uid"));  //注意这里改成了uid
                list.add(aClass);
            }
        }catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            super.closeAll(conn,null,rs);
        }
        return list;
    }

}
